/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Controllers
{
	using System;
	using System.Globalization;
	using System.Text;
	using System.Xml;
	using GearBlog.Web.Models;

	public class TrackBackController:ExtendedControllerBase
	{
		private int id;
		private string title;
		private string url;
		private string blogName;
		private string excerpt;
		public void Ping()
		{
			CancelView();

			if (Setting.Get().ReceiveTrackBack)
			{
				//No view response required

				if (IsValidRequest())
				{
					PostTrackBack();
					SendResponse(0, string.Empty);
				}
			}
			else
				SendResponse(6, "Track Back disabled");
		}
		private bool IsValidRequest()
		{
			if (!int.TryParse(Params["id"], out id))
				return SendResponse(1,"Entry id invalid or missing");

			title = Request.Form["title"];
			url = Request.Form["url"];
			blogName = Request.Form["blog_name"];
			excerpt = Request.Form["excerpt"];

			if (string.IsNullOrEmpty(title))
				return SendResponse(2,"Title missing");

			if (string.IsNullOrEmpty(url))
				return SendResponse(3, "Url missing");

			try
			{
				new Uri(url);
			}
			catch (UriFormatException)
			{
				return SendResponse(4,"Url invalid");
			}

			if (string.IsNullOrEmpty(blogName))
				return SendResponse(5,"Blog name missing");

			return true;
		}
		private bool SendResponse(int code, string message)
		{
			XmlDocument d = new XmlDocument();
			XmlElement root = d.CreateElement("response");
			d.AppendChild(root);
			XmlElement er = d.CreateElement("error");
			root.AppendChild(er);
			er.AppendChild(d.CreateTextNode(code.ToString(CultureInfo.InvariantCulture)));
			if (message.Length > 0)
			{
				XmlElement msg = d.CreateElement("message");
				root.AppendChild(msg);
				msg.AppendChild(d.CreateTextNode(message));
			}
			d.Save(Context.Response.Output);
			Context.Response.Output.Flush();

			return code == 0;
		}
		private void PostTrackBack()
		{
			Comment comment=new Comment();
			comment.Post = Post.Find(id);

			StringBuilder builder=new StringBuilder();
			builder.AppendFormat("Track Back from {0}\n\"{1}\":{2}\n{3}", blogName, title, url, excerpt);

			comment.Content = builder.ToString();
			
			comment.AuthorName = blogName;

			comment.Save();

			
			
		}
	}
}
